package com.hqyj.springboot.modules.common.service.impl;

import com.hqyj.springboot.config.ResourceConfigBean;
import com.hqyj.springboot.modules.common.service.ImageService;
import com.hqyj.springboot.modules.common.vo.Result;
import com.hqyj.springboot.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
public class ImageServiceImpl implements ImageService {
private final static Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);
    @Autowired
    private ResourceConfigBean resourceConfigBean;

    @Value("${project.artifactId}")
    private String artifactId;

    @Override
    public Result<String> uploadImage(MultipartFile file, String imageTypeName) {

        //判断图片是否为空

        if (file.isEmpty()){
            return new Result<>(Result.ResultStatus.FAILD.code, "File is empty.");

        }
        //对图片进行校验

        if (!FileUtil.isImage(file)){
            return new Result<>(Result.ResultStatus.FAILD.code, "Please select a image.");

        }
        String imageName = String.format("%s.%s",
                System.currentTimeMillis(),
                FileUtil.getFileType(file.getOriginalFilename()));

        //构建目标文件夹，如果不存在则创建
        String destFolder = String.format("%s%s/%s",
                System.getProperty("os.name").toLowerCase().startsWith("win")
                        ? resourceConfigBean.getLocalPathForWindow()
                        :resourceConfigBean.getLocalPathForLinux()
                ,artifactId,imageTypeName

        );
        File destFolderFile = new File(destFolder);
        if (!destFolderFile.exists()){
            destFolderFile.mkdirs();
        }

        //构造图片存放的绝对路径

        String destPath = String.format("%s/%s",
                destFolderFile,imageName);

        //构造图片相对路径

        String relativePath = String.format("%s%s/%s/%s",
                resourceConfigBean.getResourcePath(),
                artifactId,imageTypeName,imageName);

        //保存图片

        try {
            file.transferTo(new File(destPath));

        } catch (IOException e) {

            e.printStackTrace();
            LOGGER.info(e.getMessage());
            return new Result<>(Result.ResultStatus.FAILD.code, "Upload image failed.");

        }
        //返回结果集

        return new Result<>(Result.ResultStatus.SUCCESS.code, "Upload success.",relativePath);


    }
}
